package org.zcl.utils;

/**
 * .
 *
 * @author zhuchenglin
 * @since 2024/6/18 18:20
 */
public class RedisLua {
    public static final String REDUCE_INVENTORY;

    public static final String ADD_INVENTORY;

    static {
        /**
         * @params 库存key
         * @return
         *      -4:代表库存传进来的值是负数（非法值）
         *      -3:库存未初始化
         *      -2:库存不足
         *      -1:库存为0
         *      大于等于0:剩余库存（扣减之后剩余的库存）
         */
        REDUCE_INVENTORY = "if (redis.call('exists', KEYS[1]) == 1) then" +
                "    local stock = tonumber(redis.call('get', KEYS[1]));" +
                "    local num = ARGV[1];" +
                "    if (num <= 0) then" +
                "        return -4;" +
                "    end;" +
                "    if (stock <= 0) then" +
                "        return -1;" +
                "    end;" +
                "    if (stock >= num) then" +
                "        return redis.call('incrBy', KEYS[1], 0 - num);" +
                "    end;" +
                "    return -2;" +
                "end;" +
                "return -3;";


        /**
         * @params 库存key
         * @return
         *      -4:代表库存传进来的值是负数（非法值）
         *      -3:库存未初始化
         *      大于等于0:剩余库存（新增之后剩余的库存）
         */
        ADD_INVENTORY = "if (redis.call('exists', KEYS[1]) == 1) then" +
                "    local num = ARGV[1];" +
                "    if (num < 0) then" +
                "        return -4;" +
                "    end;" +
                "        return redis.call('incrBy', KEYS[1], num);" +
                "end;" +
                "return -3;";
    }
}
